#include <dirent.h>
#include <sys/stat.h>
#include "t0022-0.h"
#include "cui.h"
#include "dxtviewer.h"
#include "cui_messagebox.h"

#define MODNAME             "[APMEN]"
#define CONFIGS_PATH        "/data/configs"
extern struct dxtviewer_st dv;

static int appmenu_get_configs(const char *dirpath, char ***filepathlist)
{
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    int filecount = 0;
    int filepathlistlength = 0;

#define FILEPATH_ALLOC_COUNT     64

    dir = opendir(dirpath);
    *filepathlist = zmalloc(sizeof(char*) * FILEPATH_ALLOC_COUNT);
    filepathlistlength = FILEPATH_ALLOC_COUNT;
    if (filepathlist == NULL) {
        ERRSYS_INFOPRINT("malloc filepathlist failed:(%s)\n", strerror(errno));
        return 0;
    }

    if (dir == NULL) {
        ERRSYS_INFOPRINT("open directory \"%s\" failed:(%s)\n", dirpath, strerror(errno));
        return 0;
    }

    while ((entry = readdir(dir)) != NULL) {
        char file_path[PATH_MAX];
        snprintf(file_path, PATH_MAX, "%s/%s", dirpath, entry->d_name);

        // 获取文件信息
        if (stat(file_path, &file_stat) == -1) {
            ERRSYS_INFOPRINT("stat \"%s\" failed:(%s)\n", file_path, strerror(errno));
            continue;
        }

        // 检查文件名是否以 .ini 结尾，并且文件是普通文件
        if (S_ISREG(file_stat.st_mode) && strlen(entry->d_name) >= 4 && strcmp(entry->d_name + strlen(entry->d_name) - 4, ".ini") == 0) {
            printf("%s\n", entry->d_name);

            if (filecount >= filepathlistlength) {
                char **tmp = zmalloc(sizeof(char*) * (filepathlistlength + FILEPATH_ALLOC_COUNT));
                int i;
                if (tmp != NULL) {
                    for (i = 0;i < filepathlistlength;i ++) {
                        tmp[i] = (*filepathlist)[i];
                    }
                    free(*filepathlist);
                    *filepathlist = tmp;
                    filepathlistlength += FILEPATH_ALLOC_COUNT;
                }
                else {
                    goto out;
                }
            }
            (*filepathlist)[filecount] = zmalloc(sizeof(char) * (strlen(entry->d_name) + 1));
            if ((*filepathlist)[filecount] != NULL) {
                strcpy((*filepathlist)[filecount], entry->d_name);
            }
            else {
                goto out;
            }
            filecount ++;
        }
    }
out:
    closedir(dir);
    return filecount;
}

int appmenu_keyevent(struct cui_widget_st* widget, int key)
{
    int retval = CUI_WIDGETEVENT_PROPAGATION;
    ERRSYS_INFOPRINT("%s:%s %s(%d) \n", widget->name, __func__, cui_key_str(key), key);
    if (key == KEY_ENTER_US || key ==  KEY_ENTER || key == KEY_SPACE) {
#if 1
        static char filepath[PATH_MAX] = {0};
        const char *name;
        struct cui_menu_st *cmenu = widget->widgetinstance;
        ITEM *cur_item = current_item(cmenu->menu);

        name = item_name(cur_item);
        ERRSYS_INFOPRINT("[%s] You selected: %s\n", widget->name, name);
        snprintf(filepath, PATH_MAX, "%s/%s", CONFIGS_PATH, name);
        if (appdata_load(filepath) < 0) {
            messagebox(MESSAGEBOX_MSGLEVEL_ERROR, MESSAGEBOX_BUTTON_OKCANCEL, "Fail to open %s", name);
        }
#else
        appdata_load(A9999_0_DXT_CONFFILE);
#endif
        retval = CUI_WIDGETEVENT_HANDLED;
    }
    else if (KEY_ESC == key) {
        ;
    }
    
    return retval;
}

/*
* 经过EXPORT_WIDGET_INITIALIZE声明的<widgetname>_initialize函数会被cui作为widget的初始化函数自动调用，
* <widgetname>_initialize为widget的函数名字规则，widgetname和json中窗口attriubte字段的name字段一致。
*/

int appmenu_initialize(struct cui_widget_st* widget)
{
    int nconfigs = 0;
    char **filepathlist = NULL;
    int i;
    struct cui_menu_st *cmenu = widget->widgetinstance;
    char title[CUI_WIDGETTITLE_BUFLEN] = {0};

    ERRSYS_INFOPRINT("searching configs under directory \"%s\"\n", CONFIGS_PATH);
    nconfigs = appmenu_get_configs(CONFIGS_PATH, &filepathlist);
    for (i = 0;i < nconfigs;i ++) {
        ERRSYS_INFOPRINT("%s\n", filepathlist[i]);
    }
    ERRSYS_INFOPRINT("total %d configs found\n", nconfigs);
    snprintf(title, CUI_WIDGETTITLE_BUFLEN, "%s", T0022_BANNER_VERSION);
    cui_set_widget_title(widget, title);
    cui_menu_initialize(widget, nconfigs, (const char **)filepathlist, NULL, -1);
    cui_widget_align(widget, CUI_WIDGET_ALIGNMENT_XYMID);
    
    ERRSYS_INFOPRINT("nmenu %d %p\n", cmenu->nitems, cmenu->items);

    return 0;
}
EXPORT_WIDGET_INITIALIZE(appmenu_initialize);